<template>
  <div class="createTest testPaper" @click.self="edit(-1,-1)">
    <div class="w">
      <div class="header"></div>

      <!-- 试卷信息 -->
      <div class="title">
        <el-input v-model="testData.examName" class="testName" placeholder="请输入内容"></el-input>

        <ul>
          <li class="test-info">出卷者: {{ testData.creatorName }}</li>
          <li class="test-info">
            答题时间:
            <el-input-number v-model="testData.time" controls-position="right" :step="10" size="mini" :min="1" />
            分钟
          </li>
          <li class="test-info">题目数量: 共 {{ topicNavIndex_mixin(4,sortedTopics[4].topic_content.length-1) }} 道</li>
          <li class="test-info">总分: {{ totalScore }} 分</li>
          <li class="test-info">
            及格分数:
            <el-input-number v-model="testData.passMark" controls-position="right" :step="1" size="mini" :min="0"  />
            分
          </li>
          <!-- <li class="test-info">所属班级: {{ testData.classes_name }}</li> -->
          <li style="clear:both;"></li>
        </ul>
        <ul>
          <li class="test-info">允许学生切换页面次数:
            <el-input-number v-model="testData.switchPage" controls-position="right" :step="1" size="mini" :min="-1" />
            <el-tooltip class="item" effect="light" content="-1表示允许学生无限次切换页面" placement="bottom-start">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </li>
          <li class="test-info">是否允许复制文本:
            <el-switch v-model="testData.permitCopy" active-color="#409EFF" inactive-color="#ccc"> </el-switch>
          </li>
          <li class="test-info">是否打乱题目顺序:
            <el-switch v-model="testData.disruptOrder" active-color="#409EFF" inactive-color="#ccc"> </el-switch>
          </li>
          <li class="test-info">是否自动评分:
            <el-switch v-model="testData.autoMack" active-color="#409EFF" inactive-color="#ccc"> </el-switch>
            <el-tooltip class="item" effect="light" content="取消自动评分系统依然会自动批改,但会先显示分数为0分,等待教师审批确认" placement="bottom-start">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </li>
          <li class="fr">
<!--            <el-button v-if="testData.releasing === 0 || params.type === 'add'" size="mini" type="primary" @click="submit()">保存试卷</el-button>-->
<!--            <el-button v-else size="mini" type="primary" @click="copy()">复制试卷</el-button>-->
          </li>
          <li style="clear:both;"></li>
        </ul>

      </div>


      <a href="http://101.133.236.126:8089/getExcel" >下载excel模板</a>

      <el-form>
<<<<<<< HEAD
        <el-form-item prop="file">
=======
        <el-form-item label="导入学生名单，只支持xls格式文件" prop="file">
>>>>>>> 09d5960b9b929f563db4fdcbc46f05d9614e33e1
          <el-upload
              class="upload-demo"
              ref="upload"
              multiple
              accept=".xlsx"
              action=""
              :http-request="httpRequest"
              :file-list="fileList"
              :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary"
            >选取文件</el-button
            >
            <el-button style="margin-left:5px" size="small" type="primary" @click="submitUploadList">导入并保存试卷</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="back-top" @click="backTop_mixin()">
        <i class="el-icon-arrow-up"></i>
      </div>
    </div>
  </div>
</template>

<script>
import "@/assets/less/testPaper.less";
import testPaperMixin from "@/mixins/testPaper-mixin";

export default {
  name: "TestPaperTch",
  mixins: [testPaperMixin],
  data() {
    return {
      //按题目类型分类好的题目数据
      //题目类型==>  0:单选题  1:多选题  2:判断题  3:填空题  4:简答题
      sortedTopics: [
        { type: 0, topic_content: [], score: 0, showAllScore: false },
        { type: 1, topic_content: [], score: 0, showAllScore: false },
        { type: 2, topic_content: [], score: 0, showAllScore: false },
        { type: 3, topic_content: [], score: 0, showAllScore: false },
        { type: 4, topic_content: [], score: 0, showAllScore: false },
      ],

      // //试卷数据
      testData: {
        examId: -1,
        examName: "点击编辑试卷名称", //试卷名称
        time: 60, //答题时间
        topicNum: 0, //题目数量
        passMark: 0,
        autoMack: 1, //是否自动评分
        permitCopy: 1, //是否允许复制文本
        repeatTest: 1, //用户可重复考试次数
        switchPage: -1,
        disruptOrder: 0, //是否打乱题目顺序
        creatorName: this.$store.state.userName,
        totalScore:0
      },
      fileList: [],
      //用户数据
      userData: {
        id: "",
        name: "李子建",
      },

      //当前编辑的题目索引
      editInedx: {
        type: "-1",
        index: "-1",
        input: "-2",
      },

      topicDifficultyOptions: ["简单", "中等", "困难"], //题目难度选项

      //侧导航栏是否悬浮
      isFixed: false,
      topic_nav_style: "top:0px",
    };
  },

  computed: {
    params() {
      return this.$route.params;
    },
    //试卷总分
    totalScore() {
      var score = 0;
      this.sortedTopics.forEach((element) => {
        element.topic_content.forEach((item) => {
          // console.log(typeof(item.score));
          score += parseInt(item.score);
        });
      });
      this.testData.totalScore = score;
      return score;
    },

    //按填空符(三个下划线)划分字符串
    fillSymbolStr() {
      return function (str) {
        var q = str.split("___");
        return q;
      };
    },
  },

  created() {
    let type = this.$route.params.type;
    if (type === "add") {
    }
    if (type === "edit") {
      this.getTestPaper();
    }
  },

  mounted() {
    // 监听滚动事件，然后用handleScroll这个方法进行相应的处理
    window.addEventListener("scroll", this.handleScroll);
  },

  methods: {

    httpRequest(param) {
      console.log(param);
      let fileObj = param.file; // 相当于input里取得的files
      let fd = new FormData(); // FormData 对象
      fd.append("file", fileObj); // 文件对象


      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
          "token":localStorage.getItem("token")
        },
      };

      fd.append("test",JSON.stringify(this.testData))
      this.$http.post("/setExcel",fd).then((res) => {
      });


    },
    submitUploadList() {
      this.$refs.upload.submit();
    },



    // 复制试卷
    copy() {
      this.testData.examName = "点击编辑试卷名称";
      this.$router.push({
        name: "createExam",
        params: { type: "add", data: this.testData },
      });
      this.$message.success("复制成功");
    },

    //提交试卷



    submit() {
      /*  处理题目信息 */
      var topicData = [];
      this.sortedTopics.forEach((element) => {
        if (element.topic_content.length != 0) {
          element.topic_content.forEach((item) => {
            //深拷贝
            var newItem = JSON.parse(JSON.stringify(item));
            topicData.push(newItem);
          });
        }
      });

      //处理选择题选项
      topicData.forEach((item) => {
        var choice = "";
        item.choice.forEach((c) => {
          choice += c + "\n";
        });
        item.choice = choice.slice(0, -1);
        item.required = item.required === true ? 1:0
      });

      //处理正确答案
      for(let item of topicData) {
        if(!item.correctAnswer){
          this.$message.warning("有题目未选答案");
          return
        }
        if (item.correctAnswer instanceof Array) {
          if(item.correctAnswer.length === 1 && item.correctAnswer[0] === ''){
          this.$message.warning("有题目未选答案");
          return
        }
          var correctAnswer = "";
          item.correctAnswer.forEach((c) => {
            correctAnswer += c + "\n";
          });
          item.correctAnswer = correctAnswer.slice(0, -1);
        }
      };

      //处理试卷信息
      var testData = JSON.parse(JSON.stringify(this.testData));
      testData.topicTchDTOList = topicData;
      testData.creatorName = this.$store.state.userName;
      testData.topicNum = topicData.length;
      testData.autoMack = testData.autoMack == true ? "1" : "0";
      testData.disruptOrder = testData.disruptOrder == true ? "1" : "0";
      testData.permitCopy = testData.permitCopy == true ? "1" : "0";

      // console.log(testData);

      var request = {
        ...testData,
      };

      if (this.params.type === "edit") {
        var url = "/updateTestPaper";
      } else {
        var url = "/createTestPaper";
      }
      console.log(request);
      this.$http.post(url, request).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.msg);
          if (url == "/createTestPaper") {
            this.$router.push("/testPaperTch/" + res.data.examId);
          }
        }
      });
    },

    //编辑试卷---获取试卷信息
    async getTestPaper() {
      let params = {
        examId: this.$route.params.tp_id,
      };
      await this.$http.get("/getTestPaperByTp_id", { params }).then((res) => {
        // this.testData = res.data
        console.log("result.data ==> ", res);

        if (res.code == 200) {
          var testData = res.data;
        } else {
          return;
        }

        //处理试卷的题目数据
        testData.topicTchDTOList.forEach((item) => {
          if (item.topicType == 4 || item.topicType == 3 || item.topicType == 1) {
            item.correctAnswer = item.correctAnswer.split(/[\n]/g);
          }
          //按换行符分割字符串
          item.choice = item.choice.split(/[\n]/g);
          item.required = item.required === 1 ? true : false;
        });
        testData.autoMack = testData.autoMack == 1 ? true : false;
        testData.disruptOrder = testData.disruptOrder == 1 ? true : false;
        testData.permitCopy = testData.permitCopy == 1 ? true : false;

        this.testData = testData;
        console.log("testData ==> ", this.testData);

        //按题目类型分类并保存
        var topics = this.testData.topicTchDTOList;
        for (let i = 0; i < topics.length; i++) {
          for (let item of this.sortedTopics) {
            //     // console.log(topics[i].topicType,item.type);
            if (topics[i].topicType == item.type) {
              item.topic_content.push(topics[i]);
            }
          }
        }
        console.log(this.sortedTopics);
      });
    },

    //统一设置题目分数
    setAllScore(val, type) {
      val = parseInt(val);
      this.sortedTopics[type].topic_content.forEach((item) => {
        item.score = val;
      });
    },

    //设置当前编辑中的题目
    edit(type, index) {
      if (this.editInedx.type == type && this.editInedx.index == index) {
        console.log("拦截");
        return;
      }
      this.editInedx.type = type;
      this.editInedx.index = index;
    },

    //是否在编辑状态
    isEdit(type, index, input = -2) {
      if (
        this.editInedx.type == type &&
        this.editInedx.index == index &&
        this.editInedx.input == input
      ) {
        return true;
      } else {
        return false;
      }
    },

    //滚动事件
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop; // 滚动条偏移量
      if (scrollTop > 154) {
        this.topic_nav_style = "top:" + (scrollTop + 20) + "px";
        this.isFixed = true;
      } else {
        this.isFixed = false;
      }
    },

    //点击题号导航跳转
    topicNav(type, index) {
      var totalIndex = this.topicNavIndex_mixin(type, index) - 1;
      setTimeout(() => {
        document
          .getElementsByClassName("topic-content")
          [totalIndex].scrollIntoView({ behavior: "smooth" });
      }, 100);
      this.edit(type, index);
    },

    //新建题目
    newTopic(type) {
      this.sortedTopics[type].topic_content.push({
        u_id: this.userData.id,
        topicType: type,
        question: "这是我新建的题目",
        choice: ["选项1", "选项2", "选项3", "选项4"],
        correctAnswer: [],
        analysis: "这是答案分析",
        difficulty: "中等",
        score: 10,
        subjectId: "1",
        required: true
      });

      var time = setTimeout(() => {
        this.topicNav(type, this.sortedTopics[type].topic_content.length - 1);
        clearInterval(time);
      }, 100);
    },

    //删除当前正在编辑的题目
    delTopic() {
      var type = this.editInedx.type;
      var index = this.editInedx.index;
      this.sortedTopics[type].topic_content.splice(index, 1);
    },

    //上移或下移当前正在编辑的题目  -1:上移   1:下移
    moveTopic(n) {
      var type = this.editInedx.type;
      var index = this.editInedx.index;

      if (index == 0 && n == -1) {
        console.log("拦截");
        return;
      }
      if (index == this.sortedTopics[type].topic_content.length - 1 && n == 1) {
        console.log("拦截");
        return;
      }

      var topic = this.sortedTopics[type].topic_content[index];
      var upTopic = this.sortedTopics[type].topic_content[index + n];

      this.sortedTopics[type].topic_content.splice(index, 1, upTopic);
      this.sortedTopics[type].topic_content.splice(index + n, 1, topic);

      var time = setTimeout(() => {
        this.topicNav(type, index + n, 10);
        clearInterval(time);
      }, 100);
    },

    //删除选项
    delRadios(type, tIndex, index) {
      this.sortedTopics[type].topic_content[tIndex].choice.splice(index, 1);
    },

    //添加选项
    addRadios(type, tIndex) {
      var choiceLength =
        this.sortedTopics[type].topic_content[tIndex].choice.length + 1;
      if (choiceLength > 10) {
        this.$message({
          message: "不能再添加选项了喔!",
          type: "warning",
        });
        return;
      }
      this.sortedTopics[type].topic_content[tIndex].choice.push(
        "选项" + choiceLength
      );
    },

    //添加填空符
    addFillSymbol(tIndex) {
      var str = this.sortedTopics[3].topic_content[tIndex].question;
      // console.log(str);
      this.sortedTopics[3].topic_content[tIndex].question = str + "___";
    },

    //添加关键字
    addKeyWord(tIndex) {
      this.sortedTopics[4].topic_content[tIndex].correctAnswer.push("");
      console.log(this.sortedTopics[4].topic_content[tIndex]);
    },
  },
};
</script>
